import extention from "../utils/extention";
import tools from "../utils/tools";
import noDataTipTpl from '../templates/no_data_tip.tpl';
import showBoardItemTpl from '../templates/show_board_item.tpl';

@extention
@tools
class TabSearch {
    constructor(phoneData) {
        this.name = 'TabSearch',
        this.$tabAll = $('.J_tab .tab-item .all'),
        this.$board = $('.J_board'),
        this.$search = $('#J_search'),
        this.phoneData = phoneData;
    }

    init() {
        this.bindEvent();
    }

    bindEvent() {
        this.$search.on('input', TabSearch.throttle(this.searchHandler.bind(this), 800));
    }
    searchHandler(ev) {
        let target = TabSearch.getEvTarget(ev),
            keyword = TabSearch.trimSpace(target.value),
            data = this.getSearchData('search', this.phoneData, keyword);
        
        this.changeTab(this.$tabAll, 'current');
        this.renderList(data);
    }
    renderList(data) {
        let html = '';
        if (data.length <= 0) {
            html = TabSearch.tplReplace(noDataTipTpl, {
                text: '没有搜索到数据'
            })
        } else {
            data.forEach((item, index) => {
                html += TabSearch.tplReplace(showBoardItemTpl, {
                    id: item.id,
                    isFirst: index % 5 === 0 ? 'first' : '',
                    phone_name: item.phone_name,
                    pic: JSON.parse(item.pics)[0][0][0],
                    slogan: item.slogan.substring(0, 10),
                    default_price: item.default_price
                })
            });
        }
        this.$board.html(html);
    }
}

export default TabSearch;